import 'dart:convert';

import 'package:get/get.dart';
import 'package:jpush_flutter/jpush_flutter.dart';
import 'package:zrjz/comm/utils/ext_dart.dart';
import 'package:zrjz/globalService/user_service.dart';
import 'package:zrjz/router/page_router.dart';

import '../comm/constants/app_constant.dart';
import '../comm/utils/log_utils.dart';

/// 处理极光推送的逻辑
class JPushReceive {
  JPushReceive._internal();

  //保存单例
  static final JPushReceive _singleton = JPushReceive._internal();

  //工厂构造函数
  factory JPushReceive() => _singleton;

  /// 初始化极光推送，并设置监听回调
  void init() {
    JPush jpush = JPush();

    jpush.addEventHandler(
      // 接收通知回调方法。
      onReceiveNotification: (Map<String, dynamic> message) async {
        Log.d("flutter-jpush: onReceiveNotification: $message");
      },
      // 点击通知回调方法。
      onOpenNotification: (Map<String, dynamic> message) async {
        Log.d("flutter-jpush: onOpenNotification: $message");

        //拿到后端设置的内容Json对象
        dynamic extrasJson = message['extras'];
        dynamic extrasChildJson = extrasJson['cn.jpush.android.EXTRA'];
        Map<String, dynamic> jsonMap = jsonDecode(extrasChildJson.toString());

        //根据后端返回的type类型跳转到不同的路由页面

      },
      // 接收自定义消息回调方法。
      onReceiveMessage: (Map<String, dynamic> message) async {
        Log.d("flutter-jpush: onReceiveMessage: $message");
      },
      // 通知授权的回调
      onReceiveNotificationAuthorization: (Map<String, dynamic> message) async {
        Log.d("flutter-jpush: onReceiveNotificationAuthorization: $message");
        if (message.containsKey('isEnabled')) {

          //不管有没有开启通知权限，通知开关，先拿到 RegistrationId 赋值了再说
          final registrationId = await getRegistrationId();
          Log.d('flutter-jpush: 获取到registrationId：$registrationId');

          //设置给 RxString 对象，并保存到 UserService 中。
          UserService.to.registrationId.value = registrationId;
        } else {
          Log.d("flutter-jpush: onReceiveNotificationAuthorization 没有isEnable字段");
        }
      },

      // // 通知不显示的回调
      // onNotifyMessageUnShow: (Map<String, dynamic> message) async {
      //   Log.d("flutter-refruiter: onNotifyMessageUnShow: $message");
      // },
      // // 极光推送连接的回调
      // onConnected: (Map<String, dynamic> message) async {
      //   Log.d("flutter-refruiter: onConnected: $message");
      // },
    );

    jpush.setup(
      appKey: "23dedb30175208f894d3756f",
      channel: "developer-default",
      production: AppConstant.inProduction,
      debug: !AppConstant.inProduction, // 设置是否打印 debug 日志
    );

    //申请iOS授权
    jpush.applyPushAuthority(const NotificationSettingsIOS(sound: true, alert: true, badge: true));
  }

  /// 获取极光推送的id
  Future<String> getRegistrationId() async {
    JPush jpush = JPush();
    return jpush.getRegistrationID();
  }
}

var jpush = JPushReceive();
